import { forwardRef } from "preact/compat";
import { checkedTheme } from "../engines";
import { settings } from "../settings";
import { findFavo, isSearchFocus, wordSignal, setWord } from "../signals";
import SearchIcon from "./SearchIcon";
import LeftButton from "./LeftButton";

const SearchBar = forwardRef(
  ({ onButtonClick, onButtonPress, onSwap, search }, reference) => (
    <form onSubmit={() => search()} style={{ anchorName: "--bar" }}>
      <label
        class={`input input-md w-(--search-bar-width) ${checkedTheme.value[1]} rounded-(--search-bar-radius) p-[0]`}
      >
        <LeftButton onSwap={onSwap} />
        <input
          class={checkedTheme.value[2]}
          type="search"
          autoComplete="off"
          ref={reference}
          value={wordSignal}
          onInput={(event) => {
            setWord(event.target.value);
          }}
          onFocus={() => {
            isSearchFocus.value = true;
          }}
          onBlur={() => {
            isSearchFocus.value = false;
          }}
        />
        {findFavo.value ||
        (!settings.value.searchPart.showButtonAtEmpty &&
          wordSignal.value === "") ? (
          void 0
        ) : (
          <button
            class={`btn btn-md ${checkedTheme.value[0]} btn-circle rounded-(--search-bar-radius) *:size-5`}
            type="submit"
            aria-label="搜索"
            onClick={(event) => {
              if (wordSignal.value === "") {
                event.preventDefault();
                onButtonClick();
              }
            }}
            onContextMenu={() => onButtonPress(wordSignal.value)}
          >
            <SearchIcon />
          </button>
        )}
      </label>
    </form>
  ),
);

export default SearchBar;
